package edu.spsu.mail;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import edu.spsu.R;
import edu.spsu.utils.UIUtils;
import edu.spsu.utils.Util;

public class EmailListingActivity extends ListActivity {
	private static String TAG = EmailListingActivity.class.getName();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inbox);

		SharedPreferences sp = Util.getPref(this);
        
		String user = sp.getString("user", null);
		String pass = sp.getString("pass", null);
		
		if(EmailState.messagesRecieved())
		{
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(
				this, android.R.layout.simple_list_item_1,
				EmailState.getPrefaceArray());
			
			setListAdapter(adapter);
		}
		else if(user == null || user == "" || pass == null || pass == "")
		{
			LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            final View view = li.inflate(R.layout.login, null);
            
            new AlertDialog.Builder(this)
            .setTitle(R.string.login_message)
            .setCancelable(true)
            .setOnCancelListener(new OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialog) { finish(); }
			})
            .setView(view)
            .setNeutralButton(R.string.login, new OnClickListener() {
                    
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                            EditText et0 = (EditText)view.findViewById(R.id.username);
                            EditText et1 = (EditText)view.findViewById(R.id.password);
                                    
                            String etu = et0.getText().toString();
                            String etp = et1.getText().toString();
                                    
                            Util.connectToZimbra(EmailListingActivity.this, TAG, etu, etp);
                    }
            })
            .show();
		}
		else
		{
			Util.connectToZimbra(this, TAG);
		}

		reportLifeCycle("onCreate");
	}

	/** Called when the activity is finished. */
	@Override
	public void onDestroy() {
		super.onDestroy();

		EmailState.disconnect();
		reportLifeCycle("onDestroy");
	}

	
	private void reportLifeCycle(Object o) {

		Util.report(this, TAG, o+" completed successfully", false);
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 0, 0, "Refresh").setIcon(R.drawable.ic_menu_refresh);
		menu.add(0, 1, 0, "Settings").setIcon(android.R.drawable.ic_menu_preferences);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId())
		{
			case 0: Util.refreshInboxMessages(); break;
			case 1: break;		
		}
		return super.onOptionsItemSelected(item);
	}

	
	@Override
	protected void onListItemClick(ListView l, View v, final int position, long id) {

		final ProgressDialog pd = UIUtils.showProgressDialog(this, "Loading message...","You can click on all links, addresses and phone numbers.");

		new Thread(new Runnable(){
			@Override
			public void run() {
				
				final String header = EmailState.getMessageHeader(position);
				final SpannableString mess = EmailState.getMessage(position);
				
				runOnUiThread(new Thread() {
					public void run() {
 
						AlertDialog d = new AlertDialog.Builder(EmailListingActivity.this)
						.setTitle(header)
						.setMessage(mess)
						.show();

						((TextView)d.findViewById(android.R.id.message)).setMovementMethod(LinkMovementMethod.getInstance());

						UIUtils.hideProgressDialog(pd);
					}
				});

			}
		}).start();

		super.onListItemClick(l, v, position, id);
	}

	public void taskBarClick(View v) {
		if(v.getId() != R.id.goToMailButton)
			Util.taskBarClick(v);
	}
}